const path = require('path')
const ImageMinimizerPlugin = require('image-minimizer-webpack-plugin')
const CompressionPlugin = require('compression-webpack-plugin')

module.exports = {
  chainWebpack: config => {
    // 图片优化
    config.module
      .rule('images')
      .test(/\.(png|jpe?g|gif|svg)(\?.*)?$/)
      .use('image-webpack-loader')
      .loader('image-webpack-loader')
      .options({
        mozjpeg: { progressive: true, quality: 65 },
        optipng: { enabled: false },
        pngquant: { quality: [0.65, 0.9], speed: 4 },
        gifsicle: { interlaced: false },
        webp: { quality: 75 }
      })

    // 生产环境配置
    if (process.env.NODE_ENV === 'production') {
      // Gzip压缩
      config.plugin('compression').use(CompressionPlugin, [{
        test: /\.(js|css|html|svg)$/,
        threshold: 10240,
        minRatio: 0.8,
        deleteOriginalAssets: false
      }])

      // 图片压缩
      config.plugin('image-minimizer').use(ImageMinimizerPlugin, [{
        minimizer: {
          implementation: ImageMinimizerPlugin.imageminMinify,
          options: {
            plugins: [
              ['mozjpeg', { quality: 60, progressive: true }],
              ['pngquant', { quality: [0.6, 0.8] }],
              ['svgo', { plugins: [{ removeViewBox: false }] }]
            ]
          }
        }
      }])
    }
  },

  configureWebpack: {
    optimization: {
      splitChunks: {
        chunks: 'all',
        cacheGroups: {
          vendors: {
            name: 'chunk-vendors',
            test: /[\\/]node_modules[\\/]/,
            priority: -10,
            chunks: 'initial'
          },
          common: {
            name: 'chunk-common',
            minChunks: 2,
            priority: -20,
            chunks: 'initial',
            reuseExistingChunk: true
          }
        }
      }
    }
  }
}